/*
 * main.cpp
 *  Create structure pair of word in binary file
 *  Created on: Nov 14, 2012
 *      Author: Pongsathon Janyoi
 */
#include <stdio.h>
#include <stdlib.h>
typedef struct _struc_unit{
	char prefix;
	unsigned int  number;
}struc_unit;
typedef struct _pronun_struct{
	unsigned int *tri_phone;
	int len;
	int sound;
}pronun_struct;
pronun_struct ** pron_st;
int pron_st_len=0;
int make_binary(const char * input,const char * output){
	printf("Create Index Binary Structure.\n");
	printf("Text Input : %s",input);
	printf("Binary Output : %s",output);

	FILE * fp = fopen(input,"r");
	FILE * fw = fopen(output,"wb");

	char prefix[100];
	char number[100];
	while(!feof(fp)){
		fscanf(fp,"%s\t%s\n",prefix,number);
		unsigned int n = atoi(number);
		char d = prefix[0];
		printf("%d\t%d\n",d,n);
		struc_unit st;
		st.number = n;
		st.prefix = d;
		fwrite(&st,sizeof(struc_unit),1,fw);

	}
    fclose(fp);
    fclose(fw);

	return 0;
}
int test_read(const char* input){
	pron_st = (pronun_struct **)calloc(30000,sizeof(pronun_struct *));
	FILE * fp = fopen(input,"r");

	int i =0;
	unsigned int x[10];
	int am = 0;
	int size = 0;
	int line = 0;
	char before = 0;
	while(!feof(fp)){


		struc_unit st ;
		fread(&st,sizeof(struc_unit),1,fp);
		printf("%c\t%d\n",st.prefix,st.number);
		printf("\nline %d ",line);
		line++;
		if(st.prefix=='B'){
			if(before=='B'){
				pron_st[i] = (pronun_struct *) malloc(sizeof(pronun_struct));
				pron_st[i]->tri_phone = (unsigned int *)calloc(1,sizeof(unsigned int));
				pron_st[i]->tri_phone[0] = x[0];
				pron_st[i]->len = 1;
				i++;
			}if(before=='I' || before=='N'){
				pron_st[i] = (pronun_struct *) malloc(sizeof(pronun_struct));
				pron_st[i]->tri_phone = (unsigned int *)calloc(am,sizeof(unsigned int));
				for(int k=0;k<am;k++){
					pron_st[i]->tri_phone[k] = x[k];
				}
				pron_st[i]->len = am;
				i++;
			}
			x[0] = st.number;
			am=1;
			size = 1;
			before = 'B';
			printf("\nNew St.");
		}else{
			if(st.prefix=='N'){
				x[am]= -1;
				am++;
				x[am]= st.number;
				am++;
					before = 'N';
				size++;
			}else if(st.prefix=='I'){
					x[am]= st.number;
					am++;
					before = 'I';
			}
		}
	}


	pron_st_len =i;
	printf("\ni = %d",i);
	for(int i=0;i<pron_st_len;i++){
		printf("ID : %d St :",i);
		for(int j=0;j<pron_st[i]->len;j++){
			printf(" %d",pron_st[i]->tri_phone[j]);
		}
		printf("\n");
	}
}
int main(int argc,char * argv[]){
	if(argc<3){
		printf("usege : ./ibsbuild <input> <output>");
		exit(0);
	}
	make_binary(argv[1],argv[2]);
	test_read(argv[2]);
	printf("End.");
	return 0;
}


